﻿using System;
using System.Collections.Generic;
using System.Text;
using Sinacor.Infra.Service.Data;
using System.Data.Common;
using System.Data;

namespace RightRegistrationAddin.Classes
{
    public class Commom
    {
        public Commom()
        {
        }

        /// <summary>
        /// Verifica se o método está com a nomenclatura correta
        ///     Create (Métodos que começam com “Incluir”);
        ///     Read (Métodos que começam com "Consultar" ou "Obter");
        ///     Update (Métodos que começam com "Alterar");
        ///     Delete (Métodos que começam com "Excluir");
        ///     Execute (Métodos que começam com "Executar" ou "Processar").
        /// </summary>
        /// <param name="elementName"></param>
        /// <returns></returns>
        public String VerifyTypeOperation(String elementName)
        {
            if (elementName.Length > 4)
            {
                if (elementName.Substring(0,5) == "Obter")
                    return "R";

                if (elementName.Length > 6)
                {
                    if (elementName.Substring(0, 7) == "Incluir")
                        return "C";
                    else if (elementName.Substring(0, 7) == "Alterar")
                        return "U";
                    else if (elementName.Substring(0, 7) == "Excluir")
                        return "D";
                    else
                    {
                        if (elementName.Length > 7)
                        {
                            if (elementName.Substring(0, 8) == "Executar")
                                return "E";
                            else
                            {
                                if (elementName.Length > 8)
                                {
                                    if (elementName.Substring(0, 9) == "Consultar")
                                        return "R";
                                    else if (elementName.Substring(0, 9) == "Processar")
                                        return "E";
                                    else
                                        return String.Empty;
                                }
                                else
                                    return String.Empty;
                            }
                        }
                        else
                            return String.Empty;
                    }
                }
                else
                    return String.Empty;
            }
            else
                return String.Empty;
        }

        /// <summary>
        /// Converts the type operation.
        /// </summary>
        /// <param name="elementType">Type of the element.</param>
        /// <returns></returns>
        public String ConvertTypeOperation(String elementType)
        {
            String retorno = "";

            switch (elementType.ToString())
            {
                case "C":
                    retorno = "Create";
                    break;
                case "R":
                    retorno = "Read";
                    break;
                case "U":
                    retorno = "Update";
                    break;
                case "D":
                    retorno = "Delete";
                    break;
                case "E":
                    retorno = "Execute";
                    break;
                default:
                    retorno = String.Empty;
                    break;
            }

            return retorno;
        }

        /// <summary>
        /// Existses the service contracts.
        /// </summary>
        /// <param name="contract">The contract.</param>
        /// <returns></returns>
        public Classes.Contract ExistsServiceContracts(String contract)
        {
            try
            {
                String sqlCommand = "";

                sqlCommand = "select * from TFWDireito Where Desc_Direito = :DESC_DIREITO";

                using (OracleDataBase objConn = new OracleDataBase())
                {
                    using (DbCommand command = objConn.GetSqlStringCommand(sqlCommand))
                    {
                        objConn.AddInParameter(command, "DESC_DIREITO", DbType.String, contract);

                        IDataReader dr = objConn.ExecuteReader(command);
                        
                        Classes.Contract retorno = null;

                        if (dr.Read())
                        {
                            retorno = new Classes.Contract();
                            retorno.ServiceContract = dr["DESC_DIREITO"].ToString();
                            retorno.TextoHash = dr["TXT_HASH"].ToString();
                            retorno.TipoDireito = Convert.ToInt32(dr["Cod_tipoDireito"].ToString());
                            retorno.TipoOperacao = dr["Cod_tipo_oprc"].ToString();
                        }

                        return retorno;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao Consultar ServiceContracts: " + ex.Message);
            }
        }

        /// <summary>
        /// Retrieves the service contracts.
        /// </summary>
        /// <param name="serviceContractName">Name of the service contract.</param>
        /// <returns></returns>
        public List<Classes.Contract> RetrieveServiceContracts(String serviceContractName)
        {
            try
            {
                String sqlCommand = "";

                sqlCommand = "select * from TFWDireito Where Desc_Direito LIKE '" + serviceContractName.ToString() + "%'";

                using (OracleDataBase objConn = new OracleDataBase())
                {
                    using (DbCommand command = objConn.GetSqlStringCommand(sqlCommand))
                    {
                        IDataReader dr = objConn.ExecuteReader(command);

                        List<Classes.Contract> listRetorno = new List<Classes.Contract>();

                        while (dr.Read())
                        {
                            Classes.Contract retorno = new Classes.Contract();
                            retorno.ServiceContract = dr["DESC_DIREITO"].ToString();
                            retorno.TextoHash = dr["TXT_HASH"].ToString();
                            retorno.TipoDireito = Convert.ToInt32(dr["Cod_tipoDireito"].ToString());
                            retorno.TipoOperacao = dr["Cod_tipo_oprc"].ToString();
                            retorno.Status = Enums.Status.BaseInserted;

                            listRetorno.Add(retorno);
                        }

                        return listRetorno;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao Consultar ServiceContracts: " + ex.Message);
            }
        }


        /// <summary>
        /// Saves the service contracts.
        /// </summary>
        /// <param name="contracts">The contracts.</param>
        public Boolean SaveServiceContracts(List<Classes.Contract> contracts)
        {
            try
            {
                String sqlCommand = "";

                sqlCommand = "Insert into TFWDireito " +
                             " (Desc_Direito, Cod_tipoDireito, Cod_tipo_oprc,  TXT_HASH) " +
                             " Values (:DESC_DIREITO, :TIPODIREITO, :TIPOOPERACAO, :HASH)";

                Boolean retorno = false;

                using (OracleDataBase objConn = new OracleDataBase())
                {
                    foreach (Classes.Contract contract in contracts)
                    {
                        if (contract.Status == Enums.Status.NotInserted)
                        {
                            using (DbCommand command = objConn.GetSqlStringCommand(sqlCommand))
                            {
                                objConn.AddInParameter(command, "DESC_DIREITO", DbType.String, contract.ServiceContract);
                                objConn.AddInParameter(command, "TIPODIREITO", DbType.Int32, contract.TipoDireito);
                                objConn.AddInParameter(command, "TIPOOPERACAO", DbType.String, contract.TipoOperacao.Substring(0,1));
                                objConn.AddInParameter(command, "HASH", DbType.String, contract.TextoHash);

                                objConn.ExecuteNonQuery(command);

                                retorno = true;
                            }
                        }
                    }
                }

                return retorno;
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao Gravar ServiceContracts: " + ex.Message);
            }
        }


        /// <summary>
        /// Compares the service contract.
        /// </summary>
        /// <param name="contract">The contract.</param>
        /// <param name="listContract">The list contract.</param>
        public void CompareServiceContract(Classes.Contract contract, List<Classes.Contract> listContract)
        {
            Boolean existsContract = false;

            foreach (Classes.Contract item in listContract)
            {
                if (item.ServiceContract == contract.ServiceContract)
                {
                    existsContract = true;
        
                    if (String.IsNullOrEmpty(contract.TipoOperacao) || 
                        contract.TipoDireito != item.TipoDireito)
                        item.Status = Enums.Status.ErrorInserted;
                    else
                        item.Status = Enums.Status.Inserted;
                }
            }

            if (!existsContract)
                listContract.Add(contract);
        }


    }
}
